/**
 * 返回: ?os_api=23&device_type=MI
 * @param {*} json 
 */
function getUrlParam(json) {
    let url = "";
    for (let k in json) {
        let value = json[k] != undefined ? json[k] : "";
        url += `&${k}=${encodeURIComponent(value)}`;
    }
    return url ? '?' + url.substring(1) : "";
}

/**
 * 返回: os_api=23&device_type=MI
 * @param {*} json 
 */
function getUrlParamNoQue(json) {
    let url = "";
    for (let k in json) {
        let value = json[k] != undefined ? json[k] : "";
        url += `&${k}=${encodeURIComponent(value)}`;
    }
    return url ? url.substring(1) : "";
}

/**
 * url的格式: &os_api=23&device_type=MI 或 ?os_api=23&device_type=MI
 * 返回: json
 * @param {*} url 
 */
function getUrlJson(url) {
    url = decodeURIComponent(url);
    //正则表达式
    let gReg = new RegExp("[?&]([^&]+)=([^&]+)", 'g');
    //匹配元素数组
    let r = url.match(gReg);
    //返回param的key-value
    let param = {};
    if (r != null) {
        for (let i = 0; i < r.length; i++) {
            let tReg = new RegExp("[?&]([^&]+)=([^&]+)");
            let val = r[i].match(tReg)
            param[val[1]] = val[2];
        }
    }

    return param;
}

module.exports = {
    getUrlParam,
    getUrlParamNoQue,
    getUrlJson
}